<?php
	include("admin-commons.php");
	
	$user = $_POST['user'];
	$password = $_POST['password'];
	if (strlen($user) == 0 || strlen($password) == 0) {
		loginPage();
	} else {
		loginAttempt($user, $password);
	}
	
	/* FUNKtions */
	
	function loginPage($loginFailure = False) {	
		pageHeader();
		loginNavigation();
		contentHeader();
		echo "<h2>Administrator Login</h2>\n";
		echo "<p>Any attempt to access portions of this site, or any services, content, functionality, 
		data or information located at or through this site, without all necessary or required authorizations 
		and permissions for such access, is prohibited. HPBerry reserves the right to prosecute any entity or 
		individual making any such attempt, to the fullest extent allowed by applicable law. </p>";
		echo "<form action=\"login.php\" method=\"post\">\n";
		echo "Username:&nbsp";
		echo "<input type=\"text\" name=\"user\"/>";
		echo "</br>Password:&nbsp&nbsp";
		echo "<input type=\"password\" name=\"password\"/>";
		echo "</br></br><input type=\"submit\" value=\"Login\"/>";
		echo "</form></br>\n";
		if ($loginFailure)
			echo "</br> > Login failure, please try again.</br></br>\n";
		contentFooter("Employees only!");
	}

	function loginAttempt($user, $password) {
		$hash = $password;
		$sqlConnection = connectToDatabase();
		mysql_select_db("hpberry", $sqlConnection);
		$loginQuery = 'SELECT * FROM accounts';
		$accounts = mysql_query($loginQuery, $sqlConnection);
		while ($row = mysql_fetch_array($accounts)) {
			if($user == $row['user'] && $hash == $row['password']) {
				setcookie('user', $user, time() + 3600);
				setcookie('hash', $hash, time() + 3600);
				echo "<html>Successful login, click \n";
				echo "<a href=\"portal.php\"> here</a> to continue.\n";
				echo "</html>\n";
				die();
			} 
		}
		loginPage(True);
	}

?>